package com.microlecture.security;

import com.microlecture.entity.UserEntity;
import com.microlecture.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;


/**
 * 用户验证和权限
 * @author Administrator
 *
 */
public class AuthRealm extends AuthorizingRealm {

	Logger logger = LoggerFactory.getLogger(AuthRealm.class);


	@Autowired
    private UserService userService;

    /**
     * 权限信息
     */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		UserEntity userEntity = (UserEntity) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 根据用户名查询当前用户拥有的角色
		Set<String> roles = new HashSet<>();
		roles.add(userEntity.getRole());
        // 将权限名称提供给info
        authorizationInfo.setRoles(roles);
        return authorizationInfo;
	}

	/**
	 * 验证信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		logger.info("验证信息");
		String loginName = (String) token.getPrincipal();
		UserEntity user = userService.queryByLoginName(loginName);
		if(user == null) {
			// 用户名不存在抛出异常
			throw new UnknownAccountException();
		}
        //密码=要验证的密码+密码盐
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
        			user,
        			user.getPassword(),
        			ByteSource.Util.bytes(user.getPasswordSalt()),
        			getName()
        		);
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		session.setAttribute("baseUserInfo", user);
		return authenticationInfo;
	}
}